package exception;

import java.io.*;

/**
 * 自动关闭流
 *
 * 只有实现了java.io.AutoCloseable接口的类才能才能在try语句后的小括号中定义
 * 编译器会将在try语句后的小括号中定义的类最终编译成在finally中调用close关闭
 * 注：所有的流都实现了java.io.AutoCloseable接口
 *
 * try (流的定义或引用) {
 *     可能出现异常的代码片段
 * }catch(XXXException e){
 *     当try中出现XXXException后的解决代码
 * }
 *
 * 编译器将其编译为 try-catch-finally形式
 * */
public class TryCatchDemo2 {

    public void test1() {
        try (BufferedReader br = new BufferedReader(new InputStreamReader(
                new FileInputStream("src/exception/TryCatchDemo2.java")))) {
            String str;
            while ((str = br.readLine()) != null)
                System.out.println(str);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void test2() {
        BufferedReader br = null;
        try {
            br = new BufferedReader(new InputStreamReader(
                    new FileInputStream("src/exception/TryCatchDemo2.java")));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        try (BufferedReader br2 = br) {     // 传入引用
            String str;
            int i = 0;
            while ((str = br2.readLine()) != null) {
                System.out.println(str);
                if (++i >= 5)
                    break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("\n-----------------------------------------------\n");
        try {
            String str = br.readLine();     // 流在前边已关闭，此处会抛出异常
            System.out.println(str);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) throws FileNotFoundException {
        TryCatchDemo2 tc = new TryCatchDemo2();
        tc.test1();
        System.out.println("\n-----------------------------------------------\n");
        tc.test2();
    }
}
